"""服务器设置页面处理器模块"""

from typing import Optional
from aiohttp import web
from dashboard.data_manager import DataManager

router = web.RouteTableDef()

# 数据管理器实例，将在main.py中注入
data_manager: Optional[DataManager] = None

def set_data_manager(manager: DataManager):
    """设置数据管理器实例"""
    global data_manager
    data_manager = manager

@router.get("/settings")
async def settings_page_handler(request: web.Request):
    """设置页面"""
    html_content = '''
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>服务器设置 - Emby媒体库管理</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                color: #333;
            }
            .navbar {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 1rem 2rem;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .nav-container {
                max-width: 1200px;
                margin: 0 auto;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            
            /* 桌面端样式 */
            @media (min-width: 768px) {
                .nav-container {
                    flex-direction: row;
                    justify-content: space-between;
                }
            }
            .nav-title {
                color: white;
                font-size: 1.5rem;
                font-weight: bold;
                font-family: 'BM HANNA Pro OTF', sans-serif;
            }
            .nav-links {
                display: flex;
                gap: 2rem;
            }
            .nav-link {
                color: white;
                text-decoration: none;
                padding: 0.5rem 1rem;
                border-radius: 5px;
                transition: background-color 0.3s;
            }
            .nav-link:hover, .nav-link.active {
                background-color: rgba(255,255,255,0.2);
            }
            .container {
                max-width: 800px;
                margin: 2rem auto;
                padding: 0 2rem;
            }
            .page-title {
                text-align: center;
                margin-bottom: 2rem;
                color: #333;
            }
            .settings-form {
                background: white;
                padding: 2rem;
                border-radius: 10px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            }
            .form-group {
                margin-bottom: 1.5rem;
            }
            .form-group label {
                display: block;
                margin-bottom: 0.5rem;
                font-weight: 600;
                color: #555;
            }
            .form-group input {
                width: 100%;
                padding: 0.75rem;
                border: 2px solid #e0e0e0;
                border-radius: 5px;
                font-size: 1rem;
                transition: border-color 0.3s;
            }
            .form-group input:focus {
                outline: none;
                border-color: #667eea;
            }
            .form-group input[type="checkbox"] {
                width: auto;
                margin-right: 0.5rem;
            }
            .checkbox-group {
                display: flex;
                align-items: center;
            }
            .btn {
                padding: 0.75rem 2rem;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                font-size: 1rem;
                font-weight: 600;
                transition: all 0.3s;
                margin-right: 1rem;
                margin-top: 1rem;
            }
            .btn-primary {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
            }
            .btn-primary:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            }
            .btn-secondary {
                background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
                color: white;
            }
            .btn-secondary:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(76, 175, 80, 0.4);
            }
            .btn-danger {
                background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
                color: white;
            }
            .btn-danger:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(244, 67, 54, 0.4);
            }
            .btn:disabled {
                opacity: 0.6;
                cursor: not-allowed;
                transform: none;
                box-shadow: none;
            }
            .message {
                padding: 1rem;
                border-radius: 5px;
                margin: 1rem 0;
                display: none;
            }
            .success {
                background: #e8f5e8;
                color: #2e7d32;
                border: 1px solid #c8e6c9;
            }
            .error {
                background: #ffebee;
                color: #c62828;
                border: 1px solid #ffcdd2;
            }
            .loading {
                text-align: center;
                padding: 2rem;
                color: #666;
            }
            .test-result {
                margin-top: 1rem;
                padding: 1rem;
                border-radius: 5px;
                display: none;
            }
            .test-success {
                background: #e8f5e8;
                color: #2e7d32;
                border: 1px solid #c8e6c9;
            }
            .test-error {
                background: #ffebee;
                color: #c62828;
                border: 1px solid #ffcdd2;
            }
        </style>
    </head>
    <body>
        <nav class="navbar">
            <div class="nav-container">
                <div class="nav-title">Mocaca</div>
                <div class="nav-links">
                    <a href="/" class="nav-link">媒体库</a>
                    <a href="/phone-playlists" class="nav-link">播放列表</a>
                    <a href="/douyin-sources" class="nav-link">数据源</a>
                    <a href="/settings" class="nav-link active">设置</a>
                </div>
            </div>
        </nav>

        <div class="container">
            <h1 class="page-title">服务器设置</h1>
            
            <div class="settings-form">
                <div id="message" class="message"></div>
                
                <form id="settings-form">
                    <div class="form-group">
                        <label for="host">Emby服务器地址</label>
                        <input type="text" id="host" name="host" placeholder="例如: 192.168.1.100" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="port">端口</label>
                        <input type="number" id="port" name="port" placeholder="例如: 8096" required>
                    </div>
                    
                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="https" name="https">
                            <label for="https">使用HTTPS</label>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="token">API令牌</label>
                        <input type="text" id="token" name="token" placeholder="Emby API访问令牌" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="name">服务器名称</label>
                        <input type="text" id="name" name="name" placeholder="例如: main">
                    </div>
                    
                    <div class="form-group">
                        <label for="user_id">用户ID（可选）</label>
                        <input type="text" id="user_id" name="user_id" placeholder="留空自动获取">
                    </div>
                    
                    <button type="button" id="test-connection" class="btn btn-secondary">测试连接</button>
                    <button type="submit" class="btn btn-primary">保存配置</button>
                    <button type="button" id="restore-defaults" class="btn btn-danger">恢复默认配置</button>
                </form>
                
                <div id="test-result" class="test-result"></div>
            </div>
        </div>

        <script>
            // 加载当前配置
            async function loadConfig() {
                try {
                    const response = await fetch('/api/settings/config');
                    const data = await response.json();
                    
                    if (data.success) {
                        const config = data.config;
                        document.getElementById('host').value = config.host || '';
                        document.getElementById('port').value = config.port || 8096;
                        document.getElementById('https').checked = config.https || false;
                        document.getElementById('token').value = config.token || '';
                        document.getElementById('name').value = config.name || 'main';
                        document.getElementById('user_id').value = config.user_id || '';
                    }
                } catch (error) {
                    showMessage('加载配置失败: ' + error.message, 'error');
                }
            }
            
            // 测试连接
            document.getElementById('test-connection').addEventListener('click', async function() {
                const button = this;
                const originalText = button.textContent;
                button.disabled = true;
                button.textContent = '测试中...';
                
                const testResult = document.getElementById('test-result');
                testResult.style.display = 'none';
                
                try {
                    // 获取表单数据
                    const config = getFormData();
                    
                    const response = await fetch('/api/settings/test-connection', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(config)
                    });
                    
                    const data = await response.json();
                    
                    testResult.style.display = 'block';
                    if (data.success) {
                        testResult.className = 'test-result test-success';
                        testResult.textContent = '✅ 连接成功! Emby版本: ' + data.version;
                    } else {
                        testResult.className = 'test-result test-error';
                        testResult.textContent = '❌ 连接失败: ' + data.error;
                    }
                } catch (error) {
                    testResult.style.display = 'block';
                    testResult.className = 'test-result test-error';
                    testResult.textContent = '❌ 测试失败: ' + error.message;
                } finally {
                    button.disabled = false;
                    button.textContent = originalText;
                }
            });
            
            // 保存配置
            document.getElementById('settings-form').addEventListener('submit', async function(e) {
                e.preventDefault();
                const submitButton = this.querySelector('button[type="submit"]');
                const originalText = submitButton.textContent;
                submitButton.disabled = true;
                submitButton.textContent = '保存中...';
                
                hideMessage();
                
                try {
                    // 获取表单数据
                    const config = getFormData();
                    
                    const response = await fetch('/api/settings/config', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(config)
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        showMessage('✅ 配置保存成功! 正在重新加载媒体库数据...', 'success');
                        
                        // 延迟后重新加载页面，让服务器有时间重新加载数据
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    } else {
                        showMessage('❌ 保存失败: ' + data.error, 'error');
                    }
                } catch (error) {
                    showMessage('❌ 保存失败: ' + error.message, 'error');
                } finally {
                    submitButton.disabled = false;
                    submitButton.textContent = originalText;
                }
            });
            
            // 恢复默认配置
            document.getElementById('restore-defaults').addEventListener('click', function() {
                if (confirm('确定要恢复默认配置吗？这将覆盖当前的所有设置。')) {
                    fetch('/api/settings/defaults', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            loadConfig();
                            showMessage('✅ 默认配置已加载', 'success');
                        } else {
                            showMessage('❌ 恢复默认配置失败: ' + data.error, 'error');
                        }
                    })
                    .catch(error => {
                        showMessage('❌ 恢复默认配置失败: ' + error.message, 'error');
                    });
                }
            });
            
            // 获取表单数据
            function getFormData() {
                return {
                    host: document.getElementById('host').value.trim(),
                    port: parseInt(document.getElementById('port').value) || 8096,
                    https: document.getElementById('https').checked,
                    token: document.getElementById('token').value.trim(),
                    name: document.getElementById('name').value.trim() || 'main',
                    user_id: document.getElementById('user_id').value.trim()
                };
            }
            
            // 显示消息
            function showMessage(text, type) {
                const message = document.getElementById('message');
                message.textContent = text;
                message.className = 'message ' + type;
                message.style.display = 'block';
            }
            
            // 隐藏消息
            function hideMessage() {
                document.getElementById('message').style.display = 'none';
            }
            
            // 页面加载完成后加载配置
            document.addEventListener('DOMContentLoaded', function() {
                loadConfig();
            });
        </script>
    </body>
    </html>
    '''
    
    return web.Response(text=html_content, content_type='text/html')

@router.get("/api/settings/config")
async def get_settings_config(request: web.Request):
    """获取当前服务器配置"""
    try:
        if not data_manager:
            return web.json_response({
                'success': False,
                'error': '数据管理器未初始化'
            }, status=500)
        
        config = data_manager.load_config()
        server_config = config.get('server', data_manager.DEFAULT_EMBY_CONFIG)
        
        return web.json_response({
            'success': True,
            'config': server_config
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

@router.post("/api/settings/config")
async def save_settings_config(request: web.Request):
    """保存服务器配置"""
    try:
        if not data_manager:
            return web.json_response({
                'success': False,
                'error': '数据管理器未初始化'
            }, status=500)
        
        config_data = await request.json()
        
        # 验证配置
        if not config_data.get('host') or not config_data.get('token'):
            return web.json_response({
                'success': False,
                'error': '服务器地址和API令牌不能为空'
            }, status=400)
        
        # 更新配置
        config = data_manager.load_config()
        config['server'] = config_data
        
        # 保存配置
        if not data_manager.save_config(config):
            return web.json_response({
                'success': False,
                'error': '保存配置失败'
            }, status=500)
        
        # 重新初始化Emby客户端并预加载数据
        await data_manager._init_emby_client()
        await data_manager.get_libraries(force_refresh=True)
        
        return web.json_response({
            'success': True,
            'message': '配置保存成功'
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

@router.post("/api/settings/test-connection")
async def test_connection_handler(request: web.Request):
    """测试服务器连接"""
    try:
        config_data = await request.json()
        
        # 验证必要的配置
        if not config_data.get('host') or not config_data.get('token'):
            return web.json_response({
                'success': False,
                'error': '服务器地址和API令牌不能为空'
            }, status=400)
        
        # 创建临时Emby客户端进行连接测试
        from embytools.emby_client import EmbyClient
        test_client = EmbyClient(config_data)
        
        try:
            # 测试连接并获取版本信息
            info = test_client.system_api.get_system_info()
            version = info.version
        except Exception as e:
            return web.json_response({
                'success': False,
                'error': f'无法连接到Emby服务器: {str(e)}'
            })
        
        return web.json_response({
            'success': True,
            'version': version
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)

@router.post("/api/settings/defaults")
async def restore_defaults_handler(request: web.Request):
    """恢复默认配置"""
    try:
        if not data_manager:
            return web.json_response({
                'success': False,
                'error': '数据管理器未初始化'
            }, status=500)
        
        # 加载默认配置
        default_config = data_manager._get_default_config()
        
        # 保存默认配置
        if not data_manager.save_config(default_config):
            return web.json_response({
                'success': False,
                'error': '保存默认配置失败'
            }, status=500)
        
        return web.json_response({
            'success': True,
            'message': '默认配置已恢复'
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)